// This script will load a comma separated list of JS files passed in as a "js" URL parameter
// e.g. (pseudo-code)
// var scripts = ["/pib-x-core.js", "/pib-x-model.js", "/pib-x.js", "/test/my-accounts/test-parse-my-accounts.js"];
// var jsParam = scripts.join(",");
// <script src="/test/test-loader.js?js=" + jsParam></script>

(function() {
    var head = document.getElementsByTagName("head")[0];

    var getUrlParams = (function() {
        var urlParams,
        prevUrl;

        function parseParams(url) {
            var match,
            pl = /\+/g, // Regex for replacing addition symbol with a space
                search = /([^&=]+)=?([^&]*)/g,
                decode = function(s) {
                    return decodeURIComponent(s.replace(pl, " "));
                },
                idx = url.indexOf("?"),
                query = (idx > -1) ? url.substring(idx + 1) : "";

            urlParams = {};
            while (match = search.exec(query)) {
                urlParams[decode(match[1])] = decode(match[2]);
            }
        }

        return function(url) {
            if (url !== prevUrl) {
                parseParams(url);
            }
            prevUrl = url;
            return urlParams;
        };
    }());

    /**
     * Gets the src attribute of the last <script> in <head>.
     */
    function getThisScriptSrc() {
        var scripts = head.getElementsByTagName("script");
        if (!scripts || scripts.length < 1) {
            return null;
        }
        var script = scripts[scripts.length - 1];
        return script.src;
    }

    /**
     * @return The path to the script. E.g.
     *         "http://localhost/bookmarklets/common" is returned for
     *         "http://localhost/bookmarklets/common/js-loader.js?js=../infoq/infoq.js".
     */
    function getRoot(scriptSrc) {
        var parts = scriptSrc.split("?");
        parts = parts[0].split("/");
        parts = parts.splice(0, parts.length - 1);
        var src = parts.join("/");
        return src;
    }

    function addScripts(root, scripts, preventCaching, idx) {
        idx = idx || 0;
        if (idx >= scripts.length) {
            return;
        }
        var script = document.createElement("script");
        var src = root + jsFiles[idx];

        if (preventCaching) {
            // add a timestamp query string param to the js src to prevent caching
            var ts = new Date().getTime();
            if (src.indexOf("?") < 0) {
                src += "?";
            }
            src += "ts=" + ts;
        }

        var onScriptLoad = function(e) {
                e.target.removeEventListener("load", onScriptLoad);
                addScripts(root, scripts, preventCaching, idx + 1);
            };

        script.addEventListener("load", onScriptLoad, false);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", src);
        head.appendChild(script);
    }

    var src = getThisScriptSrc();
    if (null === src) {
        throw new Error("Could not get loader script's src.");
    }
    var root = getRoot(src);
    var urlParams = getUrlParams(src);
    var jsMatch = urlParams.js;
    if (!jsMatch) {
        throw new Error("'js' URL param not found");
    }

    var grimbo = (window["grimbo"] = window["grimbo"] || {});
    grimbo.bookmarklets = {};
    grimbo.bookmarklets.root = root;

    var jsFiles = jsMatch.split(",");
    addScripts(root, jsFiles, !! urlParams.cacheBust);
})();